package com.rocky.study.generic;


import java.util.Arrays;


public class DynamicArray<E> {

    private static final int DEDAULT_CAPACITY = 10;

    private int size;

    private Object[] elementData;

    public DynamicArray() {
        this.elementData = new Object[DEDAULT_CAPACITY];
    }

    private void ensureCapacity(int minCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity >= minCapacity) {
            return;
        }
        int newCapacity = oldCapacity * 2;
        if (newCapacity < minCapacity) {
            newCapacity = minCapacity;
        }
        this.elementData = Arrays.copyOf(elementData,newCapacity);
    }

    public void add(E e) {
        ensureCapacity(size + 1);
        elementData[size++] = e;
    }

    /**
     * 这个方法有一定的限制
     * @param c
     */
    public void addAllofRange(DynamicArray<E> c) {
        for (int i = 0; i < c.size; i++) {
            add(c.get(i));
        }
    }

    /**
     * E是类型参数,T是addAll的类型参数,T的上界限定为E
     * @param c
     * @param <T>
     */
    public <T extends  E> void addAll(DynamicArray<T> c) {
        for (int i = 0; i < c.size; i++) {
            add(c.get(i));
        }
    }


    public E get(int index) {
        return (E) elementData[index];
    }

    public int size() {
        return this.size;
    }

    public E set(int index,E element) {
        E oldValue = get(index);
        this.elementData[index] = element;
        return oldValue;
    }

}
